﻿using CWD.DAL.DBUtility;
using System;
using System.Configuration;
using System.Windows.Forms;
using ZXing;
using ZXing.Common;
using CWD.RPT;
using CWD.XSD;
using System.IO;
using System.Drawing;
using System.Data;
using CWD.BLL;
using System.Linq;

namespace CWD
{
    public partial class fmRetab : Form
    {
        public fmRetab()
        {
            InitializeComponent();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            string connectstr = ConfigurationManager.ConnectionStrings["ERPDB"].ToString();
            DbHelperSQL db = new DbHelperSQL(connectstr);
            string sql = string.Format("select inv.cInvCode,inv.cInvName,inv.cInvStd,inv.cInvDefine1,cs.iQuantity,cs.cBatch,pl.PacketNo from CurrentStock cs left join EKK..C_PoMateriallist pl on cs.cInvCode=pl.InvCode and cs.cBatch=pl.BatchNo left join Inventory inv ON cs.cInvCode=inv.cInvCode where cs.iQuantity>0 and pl.PacketNo='{0}'", tbPacketNo.Text);
            DataSet dsTab = db.Query(sql);
            if (dsTab.Tables[0].Rows.Count == 0)
            {
                MessageBox.Show("您输入的标签不存在或已经使用结束!", "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
            string prnName =Public.GetPrinterName();
            
            MTab ds = new MTab();
            
            DataRow dr = ds.Tables[0].NewRow();
            dr["InvCode"] =dsTab.Tables[0].Rows[0]["cInvCode"].ToString();
            dr["InvName"] = dsTab.Tables[0].Rows[0]["cInvDefine1"].ToString() + dsTab.Tables[0].Rows[0]["cInvName"].ToString();
            dr["InvStd"] = dsTab.Tables[0].Rows[0]["cInvStd"].ToString();
            dr["Qty"] = dsTab.Tables[0].Rows[0]["iQuantity"].ToString() + "米";
            dr["BatchNo"] = dsTab.Tables[0].Rows[0]["cBatch"].ToString();            
            string packetno = dsTab.Tables[0].Rows[0]["PacketNo"].ToString();
            dr["PacketNo"] = packetno;
            EncodingOptions encodeOption = new EncodingOptions();
            encodeOption.Height = 130; // 必须制定高度、宽度
            encodeOption.Width = 300;

            // 2.生成条形码图片并保存
            ZXing.BarcodeWriter wr = new BarcodeWriter();
            wr.Options = encodeOption;
            wr.Format = BarcodeFormat.CODE_128; //  条形码规格：EAN13规格：12（无校验位）或13位数字
            Bitmap img = wr.Write(packetno); // 生成图片

            MemoryStream ms = new MemoryStream();
            byte[] imagedata = null;
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            imagedata = ms.GetBuffer();
            dr["BarCode"] = imagedata;
            ds.Tables[0].Rows.Add(dr);
            //fmReport fmReport = new fmReport();
            crMTab crt = new crMTab();
            crt.SetDataSource(ds);
            crt.PrintOptions.PrinterName = prnName;
            crt.PrintToPrinter(1, true, 1, ds.Tables[0].Rows.Count);
        }
    }
}
